package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/z1gotool/z1cnf/yaml2struct/yaml2go"
)

// https://github.com/Icemap/yaml2go-cli
// https://github.com/PrasadG193/yaml2go

const (
	// StupidYaml2GoStructName yaml2go library use it as root struct name
	StupidYaml2GoStructName = "Yaml2Go"

	// packageModel
	packageModel = "package %s\n\n"
)

func StructReplace(structContent, structName, packageName string) string {
	result := strings.ReplaceAll(structContent, StupidYaml2GoStructName, structName)
	return fmt.Sprintf(packageModel, packageName) + result
}

func main() {
	// go run yaml2struct.go  -input=../config.yaml -output=config.go -package=mycnf -struct=MycnfS
	var (
		inputFile   = flag.String("input", "", "input yaml file path(required) eg: ../config.yml")
		outputFile  = flag.String("output", "", "output go file path(required) eg: ../config.go")
		structName  = flag.String("struct", "Default", "struct name")
		packageName = flag.String("package", "main", "package name")
	)
	flag.Parse()

	// 检查必填参数
	if *inputFile == "" || *outputFile == "" {
		fmt.Println("错误：必须提供 -input 和 -output")
		flag.PrintDefaults() // 显示参数帮助
		os.Exit(1)
	}

	// log.Println(*inputFile, *outputFile, *structName, *packageName)

	// return

	{
		baFile, err := os.ReadFile(*inputFile)
		if err != nil {
			panic(err)
		}

		y2g := yaml2go.New()
		strStruct, err := y2g.Convert(StupidYaml2GoStructName, baFile)
		if err != nil {
			panic(err)
		}

		os.MkdirAll(filepath.Dir(*outputFile), 0644)

		strStruct = StructReplace(strStruct, *structName, *packageName)
		err = os.WriteFile(*outputFile, []byte(strStruct), 0644)
		if err != nil {
			panic(err)
		}

		// adapter for unix
		err = os.Chmod(*outputFile, 0644)
		if err != nil {
			panic(err)
		}
	}
}
